<template>
	<div class="bg-white">
		
		<!-- 弹窗【操作提示】 -->
		<u-modal 
		  ref="uModal"
		  title="平台提示"
		  v-model="show"
		  show-cancel-button
		  confirm-text="确认"
		  cancel-text="取消"
		  @confirm="SelectCommodityTask"
		>
		  <div class="u-p-20">
			  <p>您可以从拍档好物中选择一个商品作为此次接龙的商品；<br>1.若您想选择拍档好物，则点击“确认”按钮；否则，点击“取消”按钮。</p>
		  </div>
		</u-modal>
		
		<!-- 添加折扣信息 -->
		<u-modal v-model="add_show" ref="uModal1" @confirm="addDiscount" title="新增折扣信息" :async-close="true" show-cancel-button :mask-close-able="true">
			<view class="rule-form rule-form-input-right u-box u-radius-lg u-bcl-white">
				<view style="display: flex;margin-left: 20px;">
					满<u-input class="discount_info" type="number" v-model="NewDiscount.CommodityQuantity" placeholder="请输入"/>件，
					打<u-input class="discount_info" v-model="tempNewDiscountValue" @blur="checkDiscount(tempNewDiscountValue, '1')" placeholder="请输入"/>折
				</view>
			</view>
		</u-modal>
		
		<!-- 删除折扣确认框 -->
		<u-modal v-model="delete_show" :content="delContent" @confirm="delConfirm" show-cancel-button :mask-close-able="true"></u-modal>
		
		<!-- 修改折扣信息 -->
		<u-modal v-model="update_show" ref="uModal2" @confirm="updateDiscountInfo" title="修改折扣信息" :async-close="true" show-cancel-button :mask-close-able="true">
			<view class="rule-form rule-form-input-right u-box u-radius-lg u-bcl-white">
				<u-form :model="form" ref="uForm">
					<view style="display: flex;margin-left: 20px;">
						满<u-input class="discount_info" type="number" v-model="operationDiscount.CommodityQuantity"/>件，
						打<u-input class="discount_info" v-model="tempOperationDiscountValue" @blur="checkDiscount(tempOperationDiscountValue, '2')"/>折
					</view>
				</u-form>
			</view>
		</u-modal>
		
		<div class="gray-bar">
			创建接龙
		</div>
		<div class="u-pl-15 u-pr-15">
			<u-form :model="form" ref="uForm">
				<!-- 标题 -->
				<u-form-item label="标题">
					<u-input input-align="right" v-model="form.Title" placeholder="标题（最多30个字符）"/>
				</u-form-item>
				
				<!-- 描述 -->
				<u-form-item label="描述（选填）" label-position="top" prop="description">
				    <u-input
					    type="textarea"
					    placeholder="请填写接龙的详细描述"
					    maxlength="-1"
					    height="100"
					    v-model="form.Description"
				    ></u-input>
				</u-form-item>
				
				<!-- 商品原价 -->
				<u-form-item label="原价">
					<u-input input-align="right" disabled="true" v-model="form.OriginalPrice" placeholder="商品原价" />
				</u-form-item>
				
				<!-- 优惠券金额 -->
				<u-form-item label="优惠券金额" label-width="150">
					<u-input input-align="right" disabled="true" v-model="form.CouponAmount" placeholder="优惠券金额" />
				</u-form-item>
				
				<!-- 分销佣金 -->
				<u-form-item label="分销佣金" label-width="140">
					<u-input input-align="right" disabled="true" v-model="form.DistributionReward" placeholder="分销佣金" />
				</u-form-item>
				
				<!-- 单价 -->
				<u-form-item label="优惠价"label-width="120">
					<u-input input-align="right" type="number" v-model="form.UnitPrice" placeholder="好物单价" />
				</u-form-item>
				
				<!-- 商品总量 -->
				<u-form-item label="总量">
					<u-input input-align="right" type="number" v-model="form.TotalQuantity" placeholder="好物总数量" />
				</u-form-item>
				
				<!-- 关键字 -->
				<u-form-item label="关键字" label-width="120">
					<div class="u-flex u-col-center">
					  <!-- 已添加的标签列表 -->
					  <div class="u-scroll-x u-mr-5" style="width: 500rpx;">
						<u-tag
							v-for="(item, index) in KeyWordList"
							:key="index"
							:text="item.label"
							type="info"
							mode="dark"
							close-color="#828282"
							@click="onCloseTag(index)"
						></u-tag>
					  </div>
					  <!-- 添加标签按钮 -->
					  <div class="u-center">
						<u-icon
							class="u-pointer"
							name="plus-circle"
							size="46"
							@click="toTagSettingPage(KeyWordList, 1)"
						></u-icon>
					  </div>
					</div>
				</u-form-item>
				
			</u-form>
		</div>
		
		<div class="gray-bar">
			<div style="display:inline-block;float: left;width: 80%;">折扣信息</div>
			<!-- 添加折扣信息按钮 -->
			<div style="display:inline-block;float: left;height: 100rpx;width: 20%;text-align: center;">
				<u-icon
					class="u-pointer"
					name="plus-circle"
					size="46"
					@click="add_show = true"
				></u-icon>
			</div>
		</div>
		
		<div style="margin-left: 15px;">
			<u-swipe-action :show="item.show" :index="index" 
				v-for="(item, index) in DiscountList"
				:key="index" 
				@click="click"
				@open="open(item, index)"
				:options="options"
				>
				<view class="swipe-content">{{index+1}}.满{{item.CommodityQuantity}}件，打{{item.DiscountValue}}折</view>
			</u-swipe-action>
		</div>
		
		<div style="height: 10px;"></div>
		
		<div class="gray-bar">
			高级设置
		</div>
		<div class="u-pl-15 u-pr-15 u-mb-210">
			<u-form :model="form" ref="uForm" label-width="240">
				<u-form-item label="开始时间">
					<u-input v-model="form.StartTime" type="select" input-align="right" placeholder="请选择开始日期" @click="StartTime_Show = true" />
					<u-picker v-model="StartTime_Show" mode="time" :default-time="form.StartTime" @confirm="(event) => (form.StartTime = `${event.year}-${event.month}-${event.day}`)"></u-picker>
				</u-form-item>
				<u-form-item label="截止时间">
					<u-input v-model="form.EndTime" type="select" input-align="right" placeholder="请选择截止日期" @click="EndTime_Show = true" />
					<u-picker v-model="EndTime_Show" mode="time" :default-time="form.EndTime" @confirm="(event) => (form.EndTime = `${event.year}-${event.month}-${event.day}`)"></u-picker>
				</u-form-item>
				
				<!-- 接龙参与次数限制 -->
				<u-form-item label="每人参与次数设置">
					<u-input v-model="JoinNumText" type="select" input-align="right" placeholder="请选择" @click="JoinNum_Show = true" />
					<u-picker v-model="JoinNum_Show" mode="selector" :default-selector="[0]" :range="JoinNumRange" @confirm="selectJoinNum"></u-picker>
				</u-form-item>
				<!-- <u-form-item label="接龙记录查看权限">
					<u-input v-model="form.ViewPermissions" type="select" input-align="right" placeholder="请选择" @click="ViewPermissions_Show = true" />
					<u-picker v-model="ViewPermissions_Show" mode="selector" :default-selector="[0]" :range="ViewPermissionsRange" @confirm="selectViewPermissions"></u-picker>
				</u-form-item> -->
			</u-form>
		</div>
		
		<div style="height: 30px;"></div>
		
		<div style="position: fixed;bottom: 0rpx;background-color: #f5f7f7e6;width: 100%;z-index: 3;">
			<div class="u-pt-20 u-pb-40" style="width: 90%;margin: 0 auto;">
				<u-button type="success" shape="square" @click="Submit">
					确定
				</u-button>
			</div>
		</div>
	</div>
</template>

<script>

export default {

  data() {
    return {
		form: {
			SolitaireID: '',// 接龙记录唯一ID(接龙系统)
			Initiatorid: '',// 发起人id
			InitiatorName: '',// 发起人昵称
			AvatarUrl: '',// 发起人头像
			Title: '',// 接龙标题
			Description: '',// 接龙描述
			UnitPrice: '',// 单价（优惠价格 = 原价 - 优惠券金额）
			TotalQuantity: '',// 商品总数量
			Industry: '',// 行业
			KeyWord: '',// 关键字
			DiscountInfo: '',// 折扣信息
			StartTime: '',// 开始时间
			EndTime: '',// 结束时间
			CommodityNo: '',// 商品编号
			SceneAssetsId: '',// 定制ID
			SceneID: '',// 场景ID
			Status: '1',// 状态。0:废弃；1:启用；2:结束（默认1）
			CommodityPicture: '',// 拍档好物介绍图
			examType: '8',// // 接龙类型，暂时默认为8(其他类型)
			JoinNum: '1',// 接龙参与次数限制。0:不限制；1:限参与一次；
			ViewPermissions: '',// 接龙记录查看权限，0:所有人可见；1:仅发起人可见；
			OriginalPrice: '',// 商品原价
			CouponAmount: '',// 优惠券金额
			DistributionReward: '',// 分销佣金
		},
		KeyWordList: [],// 关键字
		defaultImg: 'https://dev-1308272144.cos.ap-guangzhou.myqcloud.com/202208/FILE/jielong739Dr.jpeg',
		show: false,
		StartTime_Show: false,
		EndTime_Show: false,
		JoinNum_Show: false,
		JoinNumRange: ['仅限一次','不限'],
		ViewPermissions_Show: false,
		ViewPermissionsRange: ['所有人可见','仅自己可见'],
		JoinNumText: '仅限一次',
		DiscountList: [],
		add_show: false,
		update_show: false,
		delete_show: false,
		delContent: '',
		NewDiscount: {},
		operationDiscount: {},
		operationIndex: 0,
		options: [
			{
				text: '修改',
				style: {
					backgroundColor: '#007aff'
				}
			},
			{
				text: '删除',
				style: {
					backgroundColor: '#dd524d'
				}
			}
		],
		tempNewDiscountValue: '',
		tempOperationDiscountValue: '',
		temptag: false
    };
  },

  onLoad(options) {
	  
		// 未登录跳转到登录页面
		let loginRes = this.checkLogin();
		if (!loginRes) {
		  return false;
		}
		
		// 不需要选择商品
		if(this.isNotNull(options.NoSelect) && options.NoSelect == "1"){
			if(this.isNotNull(options.CommodityNo)){
				// 获取已经过评测的好物详情
				this.getCommodityInfo(options.CommodityNo, options.ReviewDocUnid);
			} else {
				this.showMSG('error','出错啦！')
				setTimeout(() => {
					this.goBack()
				}, 2500)
			}
			
		} else {
			// 弹窗提示选择拍档好物
			this.show = true;
		}
		
		if(this.isNotNull(options.SceneAssetsId) && this.isNotNull(options.SceneID)){
			
			this.form.SceneAssetsId = options.SceneAssetsId;
			this.form.SceneID = options.SceneID;
			
			// 初始化默认开始时间和默认结束时间
			let now = new Date().getTime()
			this.form.StartTime = this.formatTimeStamp(now)
			let end_time = new Date(parseInt(now) + (7 * 24 * 3600 * 1000))
			this.form.EndTime = this.formatTimeStamp(end_time)
			
			// 初始化发起人信息
			const userInfo = uni.getStorageSync('userInfo');
			this.form.Initiatorid = userInfo.userId;// 发起人id 
			this.form.InitiatorName = userInfo.nickName;// 发起人昵称
			this.form.AvatarUrl = userInfo.avatarUrl;// 发起人头像
			
		} else {
			
		    this.showMSG('error','出错啦！')
		    setTimeout(() => {
			    this.goBack()
		    }, 2500)
		}
		
		// 保存选中的标签列表
		uni.$on("saveTagList", (tagList = []) => {
		  this.KeyWordList = tagList;
		});
		
		// 保存选中的拍档好物
		uni.$on("saveCommodityObj", (obj = {}) => {
		  // console.log("保存选中的拍档好物obj=", obj)
		  this.form.CommodityNo = obj.CommodityNo;
		  this.form.Title = obj.CommodityName;
		  this.form.Industry = obj.Industry;
		  this.form.UnitPrice = obj.UnitPrice;
		  this.form.OriginalPrice = obj.OriginalPrice;// 商品原价
		  this.form.CouponAmount = obj.CouponAmount;// 优惠券金额
		  this.form.DistributionReward = obj.DistributionReward;// 分销佣金
		  this.KeyWordList =  this.RestructuringLabel(obj.KeyWord);
		  // 如果好物介绍图为空，则使用默认图片
		  if(this.isNotNull(obj.CommodityPicture)){
			  this.form.CommodityPicture = obj.CommodityPicture;
		  } else {
			  this.form.CommodityPicture = this.defaultImg
		  }
		});
  },

  methods: {
		
		// ========== 滑动操作 start ============
		click(index, index1) {
			if(index1 == 1) {
				// 删除
				this.delContent = "确定删除此折扣吗？"
				this.delete_show = true
			} else {
				// 修改
				this.update_show = true
			}
		},
		
		// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		open(item, index) {
			this.operationDiscount = item // 记录正在操作的对象
			this.tempOperationDiscountValue = item.DiscountValue
			this.operationIndex = index // 记录正在操作的对象的下标
			for(let key in this.DiscountList){
				let id = this.DiscountList[key].id
				if(item.id == id){
					this.DiscountList[key].show = true
				} else {
					this.DiscountList[key].show = false
				}
			}
		},
		
		/**
		 * 弹窗点击确认删除
		 */
		async delConfirm(){
			this.DiscountList.splice(this.operationIndex, 1);
		},
		
		/**
		 * 修改折扣信息
		 */
		async updateDiscountInfo(){
			
			setTimeout(() => {
				
				// 如果不想关闭，而单是清除loading状态，需要通过ref手动调用方法
				this.$refs.uModal2.clearLoading();
				
				if (this.isNotNull(this.operationDiscount.CommodityQuantity) && this.isNotNull(this.tempOperationDiscountValue)) {
					// 第一个参数是要修改的数据, 第二个值是修改当前数组的哪一个字段,第三个是要修改为什么值
					this.$set(this.DiscountList[this.operationIndex], `CommodityQuantity`, this.operationDiscount.CommodityQuantity);
					this.$set(this.DiscountList[this.operationIndex], `DiscountValue`, this.tempOperationDiscountValue);
					this.DiscountList[this.operationIndex].show = false;
					this.update_show = false;// 成功添加，手动关闭
					this.temptag = false;
				} else {
					if(!this.temptag){
						this.showMSG('none', '请添加件数、折扣再提交噢！');
					}
				}
				
			}, 1000);
				
		},
		
		// ========== 滑动操作 end ============
		
		/**
		 * 新增折扣信息
		 */
		addDiscount(){
			
			setTimeout(() => {
				
				// 如果不想关闭，而单是清除loading状态，需要通过ref手动调用方法
				this.$refs.uModal1.clearLoading();
				
				if (this.isNotNull(this.NewDiscount.CommodityQuantity) && this.isNotNull(this.tempNewDiscountValue)) {
					let new_id = this.DiscountList.length + 1;
					this.DiscountList.push({
						"id": new_id,
						"CommodityQuantity": this.NewDiscount.CommodityQuantity,
						"DiscountValue": this.tempNewDiscountValue,
						"show": false
					});
					// 添加成功后，清除数据
					this.NewDiscount.CommodityQuantity = "";
					this.tempNewDiscountValue = "";
					this.add_show = false;// 成功添加，手动关闭
					this.temptag = false;
				} else {
					if(!this.temptag){
						this.showMSG('none', '请添加件数、折扣再提交噢！');
					}
				}
				
			}, 1000);
		},
		
		/**
		 * 校验折扣是否为正整数（最多两位小数）
		 */
		checkDiscount(discount, tag) {
			if (this.isNotNull(discount)) {
				
				if(parseFloat(discount).toFixed(2) > 10.0){
					if (tag == '1') {
						this.tempNewDiscountValue = "";
					}
					if (tag == '2') {
						this.tempOperationDiscountValue = "";
					}
					this.temptag = true;
					this.$u.toast("麻烦按照10以内的数字填写折扣！");
				}
				
				const reg = /^\d+(\.\d{0,2})?$/;
				if (!(reg.test(discount))) {
					if (tag == '1') {
						this.tempNewDiscountValue = "";
					}
					if (tag == '2') {
						this.tempOperationDiscountValue = "";
					}
					this.temptag = true;
					this.$u.toast("折扣数只能输入正整数，或最多保留2位小数！");
				}
			}
		},
		
		/**
		 * 前往选择拍档好物
		 */
		async SelectCommodityTask(){
			this.$u.route("/pages_private_scene2/GroupPurchase/common/selectcommodity");
		},
		
		/**
		 * 根据评测文档ID、商品ID 获取已经过评测的好物详情
		 */ 
		async getCommodityInfo(CommodityNo, ReviewDocUnid){
			const userInfo = uni.getStorageSync('userInfo')
			let result = await this.$u.api.unifyRequest({
				userId: userInfo.userId,
				nickName: userInfo.nickName,
				appid: 'GroupPurchase',
				wf_num: 'R_GroupPurchase_BL008',
				CommodityNo: CommodityNo,
				ReviewDocUnid: ReviewDocUnid,
				loading: false // 默认发起请求会有一个全局的Loading，设置false可去掉
			});
			if(result.code == 200){
			  	this.form.CommodityNo = result.data.CommodityNo;
			  	this.form.Title = result.data.CommodityName;
			  	this.form.Industry = result.data.Industry;
			  	this.KeyWordList =  this.RestructuringLabel(result.data.KeyWord);
				this.form.OriginalPrice = result.data.OriginalPrice;
				this.form.CouponAmount = result.data.CouponAmount;
				this.form.DistributionReward = result.data.DistributionReward;
				this.form.UnitPrice = result.data.UnitPrice;
				
			  	// 如果好物介绍图为空，则使用默认图片
			  	if(this.isNotNull(result.data.CommodityPicture)){
					this.form.CommodityPicture = result.data.CommodityPicture;
			  	} else {
					this.form.CommodityPicture = this.defaultImg
			  	}
				
				// 折扣信息
				if(this.isNotNull(result.data.DiscountInfo)){
					this.DiscountList = JSON.parse(result.data.DiscountInfo);
				}
			}
		},
		
		/**
		 * 选择每人参与次数设置
		 */ 
		selectJoinNum($event){
			this.JoinNumText = this.JoinNumRange[$event]
			if(this.JoinNumText == '仅限一次'){
				this.form.JoinNum = '1'
			} else if(this.JoinNumText == '不限'){
				this.form.JoinNum = '0'
			}
		},
		
		/**
		 * 选择接龙记录查看权限
		 */
		selectViewPermissions($event){
			this.form.ViewPermissions = this.ViewPermissionsRange[$event]
		},
		
		/**
		 * 提交
		 */
		async Submit(){
			
			// 标题不能为空
			if(!this.isNotNull(this.form.Title)){
				this.showMSG('none','请填写标题再提交噢！')
				return
			}
			// 描述不能为空
			if(!this.isNotNull(this.form.Description)){
				this.showMSG('none','请填写描述再提交噢！')
				return
			}
			// 关键字不能为空
			if(!this.KeyWordList.length > 0){
				this.showMSG('none','请添加关键字再提交噢！')
				return
			} else {
				// 解析标签
				this.form.KeyWord = this.ParseLabel(this.KeyWordList);
			}
			
			// 折扣信息
			this.form.DiscountInfo = JSON.stringify(this.DiscountList);
			
			const WF_formData_local = JSON.parse(JSON.stringify(this.form));
			console.log("====发布接龙团购===", WF_formData_local);
			
			const userInfo = uni.getStorageSync('userInfo');
			let result = await this.$u.api.unifyRequest({
				userId: userInfo.userId,
				nickName: userInfo.nickName,
				appid: 'GroupPurchase',
				wf_num: 'R_GroupPurchase_BL002',
				WF_formData: WF_formData_local,
				loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
			});
			if(result.code == 200){
				let docUnid = result.data;// 接龙唯一ID
				this.showMSG('success','发布成功')
				setTimeout(() => {
					// uni.reLaunch({url:'/pages_private_scene2/SceneModule/Index?SceneAssetsId='+this.form.SceneAssetsId})
					uni.reLaunch({url:'/pages_private_scene2/GroupPurchase/SolitaireDetails?docUnid='+docUnid+'&SceneAssetsId='+this.form.SceneAssetsId+'&SceneID='+this.form.SceneID})
					
				}, 2500)
			} else {
				this.showMSG('error', result.msg)
			}
		},
		
		/**
		 * 添加标签
		 */
		async toTagSettingPage(prevPageIsSelectList = [], mode = 1) {
			uni.setStorageSync("prevPageIsSelectList", prevPageIsSelectList);
			this.$u.route(`/pages_tabbar_contact/common_contact/tag?mode=${mode}`);
		},
		
		/**
		 * 移除标签
		 */
		onCloseTag(index) {
		  this.KeyWordList.splice(index, 1);
		},
		
		/**
		 * 时间戳转换成 “yyyy-MM-dd hh:mm:ss”格式
		 */
		formatTimeStamp(num){
			let date = new Date(num);
			//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			//年
			let year = date.getFullYear();
		 
			// 月
			let month = date.getMonth() + 1;
			month = month < 10 ? ('0' + month) : month; //月补0
		 
			//日
			let day = date.getDate();
			day = day < 10 ? ('0' + day) : day; //天补0
		 
			return `${year}-${month}-${day}`
		},
		
  },
  
};
</script>

<style scoped>
	.gray-bar {
		font-size: 32rpx;
		height: 100rpx;
		line-height: 100rpx;
		padding-left: 20rpx;
		background-color: #e0e0e0;
	}

	.bg-white {
		background-color: #FFFFFF;
	}

	.u-mb-210 {
		margin-bottom: 210rpx;
	}
	
	.discount_info {
		border-bottom: 1px solid black;
		border-left-width: 0;
		border-top-width: 0;
		border-right-width: 0;
		width: 50px;
		height: 30px;
		text-align: center;
		padding-left: 15px;
	}
	
	.swipe-content{
		display: flex;
		flex-direction: row;
		background: #fff;
		border-bottom: 1rpx solid #eee;
		line-height: 45px;
	}
</style>
